<template>
  <div class="app-container">
    <el-form :show-message="!($route.query.isInfo || isInfo)" ref="elForm" :disabled="$route.query.isInfo || isInfo"
      :model="formData" :rules="rules" size="medium" label-width="120px">
      <h2 style="text-align: center">改进计划</h2>
      <h4 class="form-header h4">基础信息</h4>
      <el-row :gutter="15">
        <el-col :span="8">
          <el-form-item label="管理评审计划" prop="innerManagerAuditId">
            <el-select v-model="formData.innerManagerAuditId" placeholder="请选择管理评审计划" clearable
              :style="{ width: '100%' }">
              <el-option v-for="(item, index) in planList" :key="index" :label="item.auditYear + '年度管理评审工作计划'"
                :value="item.innerManagerAuditId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <h4 class="form-header h4">
        改进计划明细
        <el-button type="primary" plain size="mini" @click="handleAdd">增行</el-button>
        <!-- <el-button type="danger" plain size="mini" @click="handleDele">删行</el-button> -->
      </h4>
      <el-table :data="formData.infoList" :border="true" style="width: 100%">
        <el-table-column label="序号" type="index" align="center" />

        <el-table-column min-width="200" label="填报人" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`infoList.${scope.$index}.userId`" :rules="rules.userId">
              <UserDialogSelection :disabled="$route.query.isInfo || isInfo" @change="changeOpen($event, scope.$index)"
                placeholder="请选择填报人" v-model="scope.row.userId"></UserDialogSelection>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column min-width="200" label="部门" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`infoList.${scope.$index}.deptId`" :rules="rules.deptId">
              <el-cascader ref="references" :style="{ width: '100%' }"
                :props="{ value: 'id', checkStrictly: true, multiple: true }" :show-all-levels="false" placeholder="请选择部门"
                v-model="scope.row.deptId" :options="deptOptions" @change="changeCascaderNums"
                @visible-change="visibleChange($event, scope.$index)"></el-cascader>
              <!-- <el-cascader
                :props="{ value: 'id', checkStrictly: true }"
                :show-all-levels="false"
                :ref="'reference' + scope.$index"
                placeholder="请选择部门"
                :style="{ width: '100%' }"
                v-model="scope.row.deptId"
                :options="deptOptions"
              ></el-cascader> -->
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column min-width="200" label="计划开始时间" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`infoList.${scope.$index}.startDate`" :rules="rules.startDate">
              <el-date-picker v-model="scope.row.startDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                :style="{ width: '100%' }" placeholder="请选择计划开始时间" clearable></el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column min-width="200" label="计划结束时间" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`infoList.${scope.$index}.endDate`" :rules="rules.endDate">
              <el-date-picker v-model="scope.row.endDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                :style="{ width: '100%' }" placeholder="请选择计划结束时间" clearable></el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column min-width="300" label="改进目标" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`infoList.${scope.$index}.improve`" :rules="rules.improve">
              <el-input v-model="scope.row.improve" placeholder="请输入改进目标"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column min-width="300" label="计划采取的改进措施、必要的纠正预防措施" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`infoList.${scope.$index}.target`" :rules="rules.target">
              <el-input v-model="scope.row.target" placeholder="请输入计划采取的改进措施、必要的纠正预防措施"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column min-width="200" label="改进区域" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`infoList.${scope.$index}.area`" :rules="rules.area">
              <el-input v-model="scope.row.area" placeholder="请输入改进区域"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column min-width="200" label="备注" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`infoList.${scope.$index}.remark`" :rules="rules.remark">
              <el-input v-model="scope.row.remark" placeholder="请输入备注"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="删除" align="center">
          <template slot-scope="scope">
            <el-button type="danger" plain size="mini" @click="handleDele(scope.$index)">删行</el-button>
          </template>
        </el-table-column>

      </el-table>
      <el-col :span="24" v-if="btnShow">
        <el-form-item label-width="0" style="text-align: center; margin-top: 30px">
          <el-button v-if="!($route.query.isInfo || isInfo)" type="primary" @click="submitForm">提交</el-button>
          <el-button :disabled="false" @click="resetForm">返回</el-button>
        </el-form-item>
      </el-col>
    </el-form>
  </div>
</template>

<script>
import { deptTreeSelect } from "@/api/system/user";

import { selectList as selectListplan } from "@/api/quality/manageAudit/plan.js";
import {
  mamagerImproveAdd,
  updategmamagerImprove,
  mamagerImproveInfo,
} from "@/api/quality/manageAudit/improvePlan.js";
export default {
  components: {},

  dicts: ["sys_manager_item"],

  props: {
    isInfo: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: "",
    },
    btnShow: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      planInfo: {},
      formData: {
        innerManagerAuditId: "",
        auditDate: undefined,
        infoList: [
          {
            item: "",
            target: "",
            remark: "",
            area: "",
            improve: "",
            endDate: "",
            startDate: "",
            deptId: "",
            userId: "",
          },
        ],
      },
      rules: {
        userId: [
          {
            required: true,
            message: "请选择填报人",
            trigger: "blur",
          },
        ],
        innerManagerAuditId: [
          {
            required: true,
            message: "请选择管理评审计划",
            trigger: "change",
          },
        ],
        endDate: [
          {
            required: true,
            message: "请选择结束时间",
            trigger: "change",
          },
        ],
        startDate: [
          {
            required: true,
            message: "请选择开始时间",
            trigger: "change",
          },
        ],
        deptId: [
          {
            required: true,
            message: "请选择部门",
            trigger: "change",
          },
        ],

        target: [
          {
            required: true,
            message: "请输入计划采取的改进措施、必要的纠正预防措施",
            trigger: "blur",
          },
        ],
        remark: [
          {
            required: false,
            message: "请输入备注",
            trigger: "blur",
          },
        ],
        improve: [
          {
            required: true,
            message: "请输入改进目标",
            trigger: "blur",
          },
        ],
        area: [
          {
            required: true,
            message: "请输入改进区域",
            trigger: "blur",
          },
        ],
      },
      deptOptions: [],
      planList: [],
      showGroup: false,
    };
  },
  computed: {},
  watch: {},
  created() {

    if (this.$route.query.planId) {
      this.formData.innerManagerAuditId = Number(this.$route.query.planId);
    }
    this.getDeptTree();
    this.getPlan();
  },
  mounted() { },
  methods: {
    chanageUser(e, i) {
      this.formData.infoList[i].user = e.nickName;
    },
    handleAdd() {
      this.formData.infoList.push({
        target: "",
        remark: "",
        area: "",
        improve: "",
        endDate: "",
        startDate: "",
        deptId: "",
        userId: "",
      });
    },
    changeOpen(e, i) {
      console.log(e, i);
      // this.formData.userList1 =
      let idList = []
      let nameList = []
      e.forEach((i) => {
        // return { userId: i.userId, userName: i.nickName };
        idList.push(i.userId)
        nameList.push(i.nickName)
      });
      console.log(idList, 'idList');
      this.formData.infoList[i].userId = idList.toString()
      this.formData.infoList[i].user = nameList.toString()
      // this.formData.userList1[i].userId.toString()
      // console.log(this.formData.userList1[i].userId,'this.formData');
    },
    changeCascaderNums(e, i) {
      console.log(e, i);
      this.showGroup = e.length > 0 ? true : false
    },
    visibleChange(e, i) {
      console.log(e);
      if (!e && this.showGroup) {
        let arr = this.$refs.references.getCheckedNodes()
        let list = []
        let label = []
        arr.forEach((item, index) => {
          list.push(item.value)
          label.push(item.label)
        })
        console.log(list);
        this.formData.infoList[i].deptIdReplace = list.toString()
        this.formData.infoList[i].deptNameReplace = label.toString()
        // console.log(this.formData.userList1[i].deptName, 'this.formData.userList1[i].deptId');
      }

    },
    handleDele(e) {
      if (this.formData.infoList.length == 1) return;
      this.formData.infoList.splice(e,1);
    },

    getPlan() {
      selectListplan().then((response) => {
        this.planList = response.data;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
        if (this.$route.query.isEdit || this.$route.query.isInfo || this.isInfo) {
          this.getinfo();
        }
      });
    },

    getinfo() {
      return mamagerImproveInfo(this.$route.query.id || this.id).then(
        (response) => {
          this.formData = response.data;
          this.formData.infoList.forEach(item => {
            let list1 = []
            item.deptId = item.deptId.split(',')
            item.deptId = item.deptId.map(i => parseInt(i))
            console.log(item.deptId, 'item.deptId');
            item.deptName = item.deptName.split(',')
            item.userId = item.userId.split(',')
            item.user = item.user.split(',')
            item.deptId.map(i => {
              list1.push(this.findParentLot(i))
            })
            item.deptId = list1
          })
        }
      );
    },
    // 创建新数组 返回
    findParentLot(id) {
      const arr = []
      this.deployIdFun(this.deptOptions, id, arr)
      return arr.reverse()
    },
    // 逻辑代码 for循环 判断相同的id 取上级ID
    deployIdFun(options, id, newArr) {
      // console.log(options);
      options.forEach((v) => {
        if (v.id === id) {
          newArr.push(id)
          // console.log(newArr, 'newArr');
          if (!v.parentId || v.parentId !== '0') {
            this.deployIdFun(this.deptOptions, v.parentId, newArr)
          }
        } else {
          if (v.children && v.children.length) {
            this.deployIdFun(v.children, id, newArr)
          }
        }
      })
    },
    submitForm() {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          let query = JSON.parse(JSON.stringify(this.formData));
          query.infoList.forEach((i) => {
            i.userId = i.userId.toString()
            i.deptId = i.deptIdReplace
            i.deptName = i.deptNameReplace
            // e.innerManagerAuditId = this.formData.innerManagerAuditId;
            // query.infoList[i].deptId =
            //   this.$refs["reference" + i].getCheckedNodes()[0].value;
            // query.infoList[i].deptName =
            //   this.$refs["reference" + i].getCheckedNodes()[0].label;
          });
          if (this.formData.innerMamagerImproveId != undefined) {
            updategmamagerImprove(query).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.resetForm();
            });
          } else {
            mamagerImproveAdd(query).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.resetForm();
            });
          }
        }
      });
    },
    resetForm() {
      this.$tab.closeOpenPage();
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-top: 20px !important;
}
</style>
